﻿using StackExchange.Profiling;
using Core.Data;
using Core.Domain;
using Core.Events;
using Core.Helpers;
using Core.Infrastructure;
using Services.Events;
using Services.Logging;
using System;
using System.Web;

namespace Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            Bootstrapper.Bootstrap();
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            // must be at head, because the BizUrlMapper must also handle static html files
            EngineContext.Current.Resolve<IEventPublisher>().Publish(new AppBeginRequestEvent
            {
                Context = HttpContext.Current
            });

            // ignore static resources
            var webHelper = EngineContext.Current.Resolve<IWebHelper>();
            if (webHelper.IsStaticResource(this.Request))
                return;

            if (DataSettingsHelper.DatabaseIsInstalled() &&
                EngineContext.Current.Resolve<StoreInformationSettings>().DisplayMiniProfilerInPublicStore)
            {
                MiniProfiler.Start();
            }
        }

        protected void Application_EndRequest(object sender, EventArgs e)
        {
            // ignore static resources
            var webHelper = EngineContext.Current.Resolve<IWebHelper>();
            if (webHelper.IsStaticResource(this.Request))
                return;

            if (DataSettingsHelper.DatabaseIsInstalled() && EngineContext.Current.Resolve<StoreInformationSettings>().DisplayMiniProfilerInPublicStore)
            {
                // stop as early as you can, even earlier with MvcMiniProfiler.MiniProfiler.Stop(discardResults: true);
                MiniProfiler.Stop();
            }

            // codehint: sm-add
            EngineContext.Current.Resolve<IEventPublisher>().Publish(new AppEndRequestEvent
            {
                Context = HttpContext.Current
            });

            //////dispose registered resources
            //////we do not register AutofacRequestLifetimeHttpModule as IHttpModule 
            //////because it disposes resources before this Application_EndRequest method is called
            //////and this case the code above will throw an exception
            //try
            //{
            //    AutofacRequestLifetimeHttpModule.ContextEndRequest(sender, e);
            //}
            //catch { }
        }


        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            // [...]
        }

        protected void Application_Error(Object sender, EventArgs e)
        {
            //disable compression (if enabled). More info - http://stackoverflow.com/questions/3960707/asp-net-mvc-weird-characters-in-error-page
            //log error
            LogException(Server.GetLastError());
        }

        protected void LogException(Exception exc)
        {
            if (exc == null)
                return;

            if (!DataSettingsHelper.DatabaseIsInstalled())
                return;

            try
            {
                var logger = EngineContext.Current.Resolve<ILogger>();
                var workContext = EngineContext.Current.Resolve<IWorkContext>();
                logger.Error(exc.Message, exc, workContext.CurrentCustomer);
            }
            catch (Exception)
            {
                //don't throw new exception if occurs
            }
        }
    }

}